package com.coda.service.impl;

import com.coda.Constant.MessageConstant;
import com.coda.common.Result;
import com.coda.exception.BaseException;
import com.coda.service.UploadService;
import com.coda.utils.OssUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@Service
@Slf4j
public class UploadServiceImpl implements UploadService {

    @Autowired
    private OssUtils ossUtils;

    private String imageUrl;


    /**
     * 商品图片上传
     */
    //todo 商品图片上传之后显示不了
    @Override
    public String uploadImage(MultipartFile file) {
        log.info("商品图片上传");

        //获取文件名
        String filename = file.getOriginalFilename();
        //获取 . 的索引
        int index = filename.lastIndexOf(".");
        //截取扩展名
        String suffix = filename.substring(index);
        //根据uuid生成新的文件名
        String newFileName = UUID.randomUUID().toString()+suffix;

        String upload=null;
        try {
            upload = ossUtils.upload(file.getBytes(),newFileName);
            this.imageUrl = upload;
            return upload;
        } catch (IOException e) {
            throw new BaseException(Result.CODE_ERR_BUSINESS, MessageConstant.IMAGE_UPLOAD_ERR);
        }
    }

    /**
     * 获取返回的url
     * @return
     */
    public String getImageUrl(){
        return imageUrl;
    }
}
